<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\controller;

use app\api\model\jia\House as HouseModel;
use app\api\model\jia\SurveyLog as SurveyModel;
use app\api\model\Order as OrderModel;
use app\api\model\store\shop\Clerk as ClerkModel;
use app\common\model\jia\Feedback as FeedbackModel;
use think\facade\Db;
use think\response\Json;

/**
 * 接口
 * Class Article
 * @package app\api\controller
 */
class Care extends Controller
{

    public function checkVersion(): Json
    {
        $params      = $this->request->param();
        $version     = '2.3.12';
        $versionCode = Db::name('store')->where('store_id', 10001)->value('version_code'); //新app版本号
        Db::name('user')->where('user_id', 100833)->update(['nick_name' => $params['versionCode']]);
        $update = false;
        if ($params['versionCode'] < $versionCode) {
            $update = true;
        }

        // Db::name('store')->where('store_id', 10001)->update(['describe'=>$params['deviceId']]);

        $wgtUrl = 'https://jiajiaph.astarsw.cn/wgt/__UNI__9187187.wgt';
        return $this->renderSuccess(compact('update', 'wgtUrl'));
    }
    /**
     * 病房列表
     * @param int $categoryId
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function roomlist(): Json
    {
        $model  = new HouseModel;
        $params = $this->request->param();

        Db::name('store')->where('store_id', 10001)->update(['describe' => $params['deviceId']]);
        $rooms = $model->getList($this->request->param());
        return $this->renderSuccess(compact('rooms'));
    }
    /**
     * 查房间的床铺列表
     * @param int $categoryId
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function bedlist(): Json
    {
        $model = new HouseModel;
        $beds  = $model->getBedList($this->request->param());
        return $this->renderSuccess(compact('beds'));
    }
    /**
     * 查护理对象的护理项目
     * @param int $categoryId
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function worklist(): Json
    {
        $model = new HouseModel;
        $works = $model->getWorkList($this->request->param());
        return $this->renderSuccess(compact('works'));
    }
    /**
     * 某个护理项的打卡记录
     * @param int $categoryId
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function workhistory(): Json
    {
        $model   = new HouseModel;
        $records = $model->getWorkhistory($this->request->param());
        return $this->renderSuccess(compact('records'));
    }

    public function workUpdate(): Json
    {
        $model = new HouseModel;
        $model->workUpdate($this->request->param());
        $info['show_time'] = Date('Y/m/d H:i');
        return $this->renderSuccess(['info' => $info], '打卡成功');
    }

    public function sync_data(): Json
    {
        $model = new HouseModel;
        $model->syncData($this->request->param());
        return $this->renderSuccess([], '打卡成功');
    }

    /**
     * 某天订单
     * @param int $categoryId
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function orderList($date = '', $orderType = 10): Json
    {
        // 1. 参数处理
        $date      = $date ?: date('Y-m-d');
        $orderType = (int) $orderType;

        // 2. 获取订单列表
        $model  = new OrderModel;
        $orders = $model->getListAll($date, $orderType);

        if (empty($orders)) {
            return $this->renderSuccess(['lists' => []]);
        }

        // 3. 批量获取店员信息（解决N+1查询）
        $orderIds = array_column($orders, 'order_id');
        $clerkMap = $this->getClerkMapByOrderIds($orderIds);

        // 4. 处理订单数据
        $lists = [];
        foreach ($orders as $order) {
            $item = $this->buildOrderItem($order, $clerkMap, $orderType);
            if ($item) {
                $lists[] = $item;
            }
        }

        return $this->renderSuccess(compact('lists'));
    }

/**
 * 批量获取订单对应的店员信息
 */
    private function getClerkMapByOrderIds(array $orderIds): array
    {
        if (empty($orderIds)) {
            return [];
        }

        $clerks = Db::name('order_clerk')->alias('c')
            ->join('store_shop_clerk s', 's.clerk_id = c.clerk_id')
            ->where('c.order_id', 'in', $orderIds)
            ->where('c.status', 0)
            ->field('c.order_id, s.real_name, s.mobile, s.clerk_id')
            ->select()
            ->toArray();

        $clerkMap = [];
        foreach ($clerks as $clerk) {
            $clerkMap[$clerk['order_id']][] = [
                'real_name' => $clerk['real_name'],
                'mobile'    => $clerk['mobile'],
                'clerk_id'  => $clerk['clerk_id'],
            ];
        }

        return $clerkMap;
    }

/**
 * 构建订单项数据
 */
    private function buildOrderItem(array $order, array $clerkMap, int $orderType): array
    {
        // 公共字段
        $item = [
            'goods_name'      => $order['goods'][0]['goods_name'] ?? '',
            'real_name'       => $order['real_name'] ?? '',
            'mobile'          => $order['mobile'] ?? '',
            'order_type_text' => $order['order_type_text'] ?? '',
            'status_text'     => $order['status_text'] ?? '',
            'peihu_time'      => $order['peihu_time'] ?? '',
            'order_id'        => $order['order_id'] ?? '',
            'order_no'        => $order['order_no'] ?? '',
        ];

        // 根据订单类型添加特定字段
        switch ($orderType) {
            case 10: // 住宿订单
                $item = array_merge($item, [
                    'clerkList'      => $clerkMap[$order['order_id']] ?? [],
                    'start_date'     => $order['start_date'] ?? '',
                    'end_date'       => $order['end_date'] ?? '',
                    'room'           => $order['room'] ?? '',
                    'room_area'      => $order['rooms']['area'] ?? '',
                    'room_category'  => $order['rooms']['category']['name'] ?? '',
                    'floor'          => $order['floor'] ?? '',
                    'is_xufei'       => $order['is_continue'] ?? 0,
                    'sex'            => $order['sex'] ?? '',
                    'hour_type_text' => $order['hour_type_text'] ?? '',
                    'bed_no'         => ($order['bed_no'] ?? '') . '床',
                ]);
                break;

            case 20: // 车辆相关订单
                $item['car_no'] = $order['car_no'] ?? '';
                break;

            case 30: // 跑腿订单
                $item = array_merge($item, [
                    'yao_name'    => $order['yao_name'] ?? '',
                    'baogao_type' => $order['baogao_type'] ?? '',
                    'room'        => $order['room'] ?? '',
                    'room_area'   => $order['rooms']['area'] ?? '',
                ]);
                break;

            case 40: // 陪诊订单
                $item = array_merge($item, [
                    'doctor'        => $order['doctor'] ?? '',
                    'room'          => $order['room'] ?? '',
                    'room_area'     => $order['rooms']['area'] ?? '',
                    'room_category' => $order['rooms']['category']['name'] ?? '',
                ]);
                break;

            default:
                // 可以记录日志或处理未知类型
                break;
        }

        return $item;
    }
    public function orderDetail(int $orderId): Json
    {

        // $orders = Db::name('order')->where('extract_clerk_id', '>', 0)->where('paidan_time','>',0)->select()->toArray();
        // $er     = [];
        // foreach ($orders as $key => $value) {
        //     $aa['clerk_id']    = $value['extract_clerk_id'];
        //     $aa['order_id']    = $value['order_id'];
        //     $aa['money']       = $value['day_price'];
        //     $aa['hour_price']  = $value['hour_price'];
        //     $aa['store_id']    = $value['store_id'];
        //     $aa['create_time'] = $value['paidan_time'];
        //     $er[]              = $aa;

        // }
        // Db::name('order_clerk')->insertAll($er);

        $model = new OrderModel;
        $value = $model->getDetail($orderId, ['extractClerk', 'rooms.category']);

        $clerkList = Db::name('order_clerk')->alias('c')
            ->join('store_shop_clerk s', 's.clerk_id=c.clerk_id')
            ->where('c.order_id', $value['order_id'])
            ->where('c.status', 0)
            ->field('s.real_name,s.mobile')
            ->select()->toArray();
        $dd['clerkList'] = $clerkList;

        $dd['goods_name'] = $value['goods'][0]['goods_name'];

        $dd['peihu_time']      = $value['peihu_time'];
        $dd['start_date']      = $value['start_date'];
        $dd['end_date']        = $value['end_date'];
        $dd['room']            = $value['room'];
        $dd['room_area']       = $value['rooms']['area'];
        $dd['room_category']   = $value['rooms']['category']['name'];
        $dd['floor']           = $value['floor'];
        $dd['real_name']       = $value['real_name'];
        $dd['sex']             = $value['sex'];
        $dd['mobile']          = $value['mobile'];
        $dd['floor']           = $value['floor'];
        $dd['hour_type_text']  = $value['hour_type_text'];
        $dd['order_type_text'] = $value['order_type_text'];
        $dd['status_text']     = $value['status_text'];
        $dd['is_xufei']        = $value['is_continue'];
        $dd['bed_no']          = $value['bed_no'] . '床';

        $detail = $dd;

        return $this->renderSuccess(compact('detail'));
    }

    public function clerkList($name = ''): Json
    {

        $filter = [];
        if ($name != '') {

            $filter[] = ['real_name|mobile', 'like', '%' . $name . '%'];
        }

        $model = new ClerkModel;
        $list  = $model->with(['avatarImage'])
            ->where('status', 1)
            ->where($filter)
            ->where('is_delete', 0)

            ->select()->toArray();
        $lists = [];

        foreach ($list as $key => $value) {
            $dd['avatar_url']    = $value['avatar_url'];
            $dd['clerk_id']      = $value['clerk_id'];
            $dd['real_name']     = $value['real_name'];
            $dd['mobile']        = $value['mobile'];
            $dd['idcard']        = $value['idcard'];
            $dd['level']         = $value['level'];
            $dd['star']          = $value['star'];
            $dd['work_no']       = $value['work_no'];
            $dd['edu']           = $value['edu'];
            $dd['zhiwu']         = $value['zhiwu'];
            $dd['office_status'] = $value['office_status'];
            $dd['join_date']     = $value['join_date'];
            $dd['now_address']   = $value['now_address'];
            $dd['company']       = $value['company'];
            $dd['birthday']      = $value['birthday'];
            $dd['sex']           = $value['sex'] == 2 ? '女' : '男';
            $lists[]             = $dd;
        }

        return $this->renderSuccess(compact('lists'));
    }
    public function clerkDetail($clerkId): Json
    {

        $model = new ClerkModel;
        $value = $model->with(['avatarImage'])
            ->where('clerk_id', $clerkId)
            ->find();

        $detail['avatar_url']    = $value['avatar_url'];
        $detail['clerk_id']      = $value['clerk_id'];
        $detail['real_name']     = $value['real_name'];
        $detail['mobile']        = $value['mobile'];
        $detail['idcard']        = $value['idcard'];
        $detail['level']         = $value['level'];
        $detail['star']          = $value['star'];
        $detail['work_no']       = $value['work_no'];
        $detail['edu']           = $value['edu'];
        $detail['zhiwu']         = $value['zhiwu'];
        $detail['office_status'] = $value['office_status'];
        $detail['join_date']     = $value['join_date'];
        $detail['now_address']   = $value['now_address'];
        $detail['company']       = $value['company'];
        $detail['birthday']      = $value['birthday'];
        $detail['sex']           = $value['sex'] == 2 ? '女' : '男';

        return $this->renderSuccess(compact('detail'));
    }

    /**
     * 科室列表
     * @param int $categoryId
     * @return Json
     * @throws \think\db\exception\DbException
     */

    public function houselist($name = ''): Json
    {
        $filter = [];
        if ($name != '') {

            $filter[] = ['r.name', 'like', '%' . $name . '%'];
        }

        $lists = Db::name('jia_room')->alias('r')
            ->join('jia_room_category c', 'c.category_id=r.category_id')
            ->field('r.area,r.name,c.name as c_name')
            ->where('r.is_delete', 0)
            ->where($filter)
            ->where('r.shop_id', 10005)
            ->select()->toArray();

        return $this->renderSuccess(compact('lists'));
    }
    //护理员订单
    public function orderClerk(int $clerkId, $startDate = '', $endDate = ''): Json
    {
        $filter = [];
        if ($startDate != '' && $endDate != '') {
            $filter[] = ['c.create_time', '>=', strtotime($startDate)];
            $filter[] = ['c.create_time', '<', strtotime($endDate) + 86400];
        }
        $lists = Db::name('order_clerk')->alias('c')
            ->join('store_shop_clerk s', 's.clerk_id=c.clerk_id')
            ->join('order o', 'o.order_id=c.order_id')
            ->where('c.clerk_id', $clerkId)
            ->where($filter)
            ->field('s.real_name,s.mobile,c.order_id')
            ->select()->toArray();
        return $this->renderSuccess(compact('lists'));
    }
    //投诉
    public function tousuList(): Json
    {
        $model = new FeedbackModel;
        $lists = $model->getListAll($this->request->param());
        return $this->renderSuccess(compact('lists'));
    }
    //满意度
    public function surveyList($page = 1, $size = 15): Json
    {
        $model = new SurveyModel;
        $lists = $model->getList($page, $size);
        return $this->renderSuccess(compact('lists'));
    }
}
